package Hot100;

import LinkedList.ListNode;

public class 相交链表 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode currA = headA, currB = headB;
        int lengthA = 0, lengthB = 0;
        while (currA != null) {
            lengthA++;
            currA = currA.next;
        }
        while (currB != null) {
            lengthB++;
            currB = currB.next;
        }
        if (lengthA > lengthB) headA = getNew(headA, lengthA - lengthB);
        else if (lengthA < lengthB) headB = getNew(headB, lengthB - lengthA);
        while (headA != headB) {
            headA = headA.next;
            headB = headB.next;
        }
        return headA;
    }

    private ListNode getNew(ListNode head, int n) {
        for (int i = 0; i < n; i++) head = head.next;
        return head;
    }
}
